<template>
    <div>
        <!-- <div>字段，值，顺序</div> -->
        <div ref="sortConditionsContainer">
            <div class="flex mb-1" v-for="(item, index) in conditions">
                <el-select
                    v-if="sortConditionsContainerRef"
                    v-model="item.field"
                    :append-to="sortConditionsContainerRef!"
                >
                    <el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>
                </el-select>
                <el-radio-group v-model="item.order" class="mx-2 w-[300px]">
                    <el-radio value="asc" size="small">升序</el-radio>
                    <el-radio value="desc" size="small">降序</el-radio>
                </el-radio-group>
                <el-button @click="removeCondition(index)" icon="delete" />
            </div>
            <div class="flex justify-center mt-2">
                <el-button @click="createCondition" icon="plus">添加</el-button>
                <el-button @click="handleReset" icon="RefreshLeft">重置</el-button>
                <el-button @click="onSave" type="primary" icon="check">确定</el-button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { IFileItem } from '@/appUtils/fs'
import { ElSelect } from 'element-plus'
import { cloneDeep, isEqual, uniqWith } from 'lodash-es'
import { ref, useTemplateRef } from 'vue'
import { IFileItemSortCondition } from '../utils/sortAndFilter'

const props = defineProps<{
    defaultConditions?: IFileItemSortCondition[]
}>()

const emit = defineEmits<{
    (e: 'change', value: IFileItemSortCondition[]): void
}>()

// console.log(props)

const options: { label: string; value: keyof IFileItem }[] = [
    { label: '文件名', value: 'name' },
    { label: '路径', value: 'path' },
    { label: '文件大小', value: 'size' },
    { label: '是否是文件夹', value: 'isDir' },
    { label: '是否是文件', value: 'isFile' },
    { label: '文件后缀名', value: 'extWithDot' },
    { label: '文件后缀名', value: 'ext' },
    { label: '文件创建时间', value: 'createTime' },
    { label: '文件修改时间', value: 'updateTime' },
    { label: '文件访问时间', value: 'accessTime' },
    { label: '是否是隐藏文件', value: 'isHidden' }
]

const conditions = ref<IFileItemSortCondition[]>(cloneDeep(props.defaultConditions || []))

const sortConditionsContainerRef = useTemplateRef('sortConditionsContainer')

// 创建
const createCondition = () => {
    conditions.value.push({
        field: 'name',
        order: 'asc'
    })
}

// 删除
const removeCondition = (index: number) => {
    conditions.value.splice(index, 1)
}

// 重置
const handleReset = () => {
    console.log([...(props.defaultConditions || [])])
    conditions.value = cloneDeep(props.defaultConditions || [])
}

// 保存
const onSave = () => {
    const uniqued = uniqWith(cloneDeep(conditions.value), isEqual)
    conditions.value = uniqued
    emit('change', uniqued)
}
</script>

<style scoped></style>
